#!/bin/bash

#
# function to output help
#
function usage
{
	echo Usage $0
	echo "	--help: display this page"
	echo "	--rsa [<bit>]: Use RSA algorithm with <bit> length (default is 1024)"
	echo "	--out <filename>: Key will be generated in <filename>"
}

#
# function to check a simple yes/no question
# returns 0 if answer is yes (or no question was asked)
# parameter $1: 0 if ask no question
# paraneter $2: question text
#
function checkyN
{
	if [ $1 -eq 0 ]
	then
		return 0
	fi
	echo $2 "(y/N)"
        read answer
        if [ "$answer" = "" ]
        then
                answer=n
        fi
        case $answer in
                Y | y | Y* | y*)
                        return 0
			;;
                n | N | n* | N*)
                        return 2
                        ;;
        esac
}

# default values
outfilename=client.key
algorithm=rsa
algname=RSA
bitlen=1024
ok=0

# check the input parameters
while [ "$1" != "" ]
do
	case $1 in
		-o | --out )	shift
				outfilename=$1
				;;
		-R | --rsa )	shift
				algorithm=rsa
				algname=RSA
				bitlen=$1
				;;
		-h | --help )	usage
				exit
				;;
		*)		echo "Unknown Parameter $1"
				usage
				exit 1
	esac
	shift
done

# check the input values
let MODULUS=$bitlen%128
if [ $MODULUS -ne 0 ]
then
	echo "Bitlength $bitlen is not a multiple of 128"
	ok=1
fi
if [ $bitlen -lt 1024 ]
then
	echo "Bitlength $bitlen is less than 1024"
	ok=1
fi
if [ $bitlen -gt 2048 ]
then
	echo "Bitlength $bitlen is greater than 2048"
	ok=1
fi

# final user confirmation
checkyN $ok "Do you really want to use this parameters?"
if [ $? -ne 0 ]
then
	exit $return
fi

# call the key generator
openssl gen$algorithm -out $outfilename $bitlen
